package eshttp

import (
	"net/http"

	"gitee.com/les49/esgo/errors"
	"github.com/zeromicro/go-zero/rest/httpx"
)

type SuccessBean struct {
	Code uint32 `json:"code"`
	Msg  string `json:"msg"`
	Data any    `json:"data,omitempty"`
}

type ErrorBean struct {
	Code int64  `json:"code"`
	Msg  string `json:"msg"`
}

func Success(data any) *SuccessBean {
	return &SuccessBean{200, "success", data}
}

func Error(errCode int64, errMsg string) *ErrorBean {
	return &ErrorBean{errCode, errMsg}
}

func Result(w http.ResponseWriter, r *http.Request, resp any, err error) {
	if err == nil {
		r := Success(resp)
		httpx.WriteJson(w, http.StatusOK, r)
	} else {
		er := errors.Fmt(err)
		httpx.WriteJson(w, http.StatusBadRequest, Error(er.Code, er.Msg))
	}
}
